#pragma once

#include<iostream>
#include"Socket.hpp"
#include<sys/select.h>
#include<sys/time.h>

using namespace std;

static const uint16_t defaultport = 8080;

class SelectServer
{
public:
    SelectServer(uint16_t port = defaultport)
    :_port(port)
    {}

    ~SelectServer()
    {}
public:
    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();

        return true;
    }

    void HandlerEvent(fd_set &fs)
    {

    }

    void Start()
    {
        int listensock = _listensock.GetFd();
        while(true)
        {
            //这里不能使用accept,新连接来了，相当于读时间到来
            fd_set rfds;
            FD_ZERO(&rfds);
            FD_SET(listensock, &rfds);

            struct timeval timeout = {1, 0};
            //如果事件就绪，上层不提醒，select会一直提醒你
            // fd_set wfds;
            // fd_set exception;
            int n = select(listensock, &rfds, nullptr, nullptr, &timeout);
            switch(n)
            {
                case 0:
                    cout<<"time out, timeout: "<<timeout.tv_sec<<endl;
                    break;
                case -1:
                    cerr<<"select error"<<endl;
                    break;
                default:
                    //有事件就绪
                    cout<<"get a new link"<<endl;
                    HandlerEvent(rfds);
                    break;
            }
        }
    }

    void Close()
    {
        _listensock.Close();
    }
private:
    Sock _listensock;
    uint16_t _port;
};

